package main

import (
	"archive/zip"
	"code.google.com/p/mahonia"
	"flag"
	"fmt"
	"io"
	"os"
	"regexp"
	//"strings"
)

var debug = true
var targetEncoding string
var filename string

func init() {
	flag.StringVar(&targetEncoding, `e`, `utf8`, `source zip file encoding type,default to utf8`)
	flag.StringVar(&filename, `f`, ``, `source zip file name`)
}
func main() {
	flag.Parse()
	if filename == `` {
		fmt.Println(`Please input zip file name`)
		os.Exit(1)
	}
	dec := mahonia.NewDecoder(targetEncoding)
	if dec == nil {
		fmt.Println(`Error:`, `No Such Encoding Type:`, targetEncoding)
		os.Exit(1)
	}
	zipacv, err := zip.OpenReader(filename)
	if err != nil {
		fmt.Println("Fatal: ", err)
		os.Exit(1)
	}
	defer zipacv.Close()
	reg := regexp.MustCompile(`^((?:[^/]+/)*)([^/]+)$`)
	for _, v := range zipacv.File {
		rawname := dec.ConvertString(v.FileHeader.Name)
		if debug {
			fmt.Printf(`extracting: %v`, rawname)
			if v.Comment != `` {
				fmt.Printf(`with comment: %v`, v.Comment)
			}
			fmt.Println(``)
		}
		if v.FileInfo().IsDir() {
			if debug {
				fmt.Println(v.FileHeader.Name, `is dir, creating dir:`, rawname)
			}
			err = os.MkdirAll(rawname, 0755)
			if err != nil {
				fmt.Println(`Error:`, err)
				os.Exit(1)
			}
			continue
		}

		fpath, fname := ``, ``
		regname := reg.FindStringSubmatch(rawname)
		for _, u := range regname[1 : len(regname)-1] {
			fpath += u
		}
		fname = regname[len(regname)-1]

		if fpath != `` {

			err = os.MkdirAll(fpath, 0755)
			if err != nil {
				fmt.Println(`Error:`, err)
				os.Exit(1)
			}
		}
		f, err := os.Create(fpath + fname)
		if err != nil {
			fmt.Println(`Error:`, err)
			os.Exit(1)
		}
		zipf, _ := v.Open()
		_, err = io.Copy(f, zipf)
		if err != nil {
			fmt.Println(`Error:`, err)
			os.Exit(1)
		}
		zipf.Close()
		f.Close()

	}

}
